package com.gupao.vip.nio.buffer;

import java.io.FileInputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @创建人 majingang
 * @联系方式 aoyouxingkong08@163.com
 * @创建日期 2020-04-15
 * @描述
 */
public class BufferDemo {
    /**
     * 打印缓冲区的实时状态：容量，当前操作位置，操作范围索引
     * @param step
     * @param buffer
     */
    public static void output(String step, Buffer buffer){
        System.out.println(step + " : ");
        System.out.println("capacity : " + buffer.capacity() + ", ");
        System.out.println("position : " + buffer.position()  + ", ");
        System.out.println("limit : " + buffer.limit());
        System.out.println();

    }

    public static void main(String[] args) throws Exception{
        //文件IO处理
        FileInputStream fileInputStream = new FileInputStream("c:\\LibAntiPrtSc_ERROR.log");

        //创建文件操作管道
        FileChannel fileChannel = fileInputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(10);
        output("初始化", buffer);

        //先读一下
        fileChannel.read(buffer);
        output("调用read()", buffer);

        //准备操作前，先锁定操作范围
        buffer.flip();
        output("调用flip()", buffer);

        //判断有没有可读数据
        while(buffer.hasRemaining()){
            byte b = buffer.get();
            System.out.print((char)b);
        }
        System.out.println();
        output("调用get()", buffer);

        //可以理解为解锁
        buffer.clear();
        output("调用clear()", buffer);

        //关闭管道
        fileInputStream.close();
    }
}
